    import { Injectable } from '@angular/core';
    import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http';
    import { Observable } from 'rxjs/internal/Observable';
    import { AppSettings } from '../config/app-settings';
    import * as _ from 'lodash';
    @Injectable({
        providedIn: 'root'
    })
    export class AttachmentUtilsService {

        constructor(private httpClient: HttpClient) { }


        uploadFile(attachment, deleteOrigin = false): Observable<any> {
            let entity = attachment.entity || {};
            let belongToID = attachment.belongToID;
            let belongToCategory = attachment.belongToCategory;
            let files = attachment.files;
            //delete origin ids if necessary
            if(deleteOrigin){
                let deleteIDs = this.getOriginalAttachmentIDs(entity[belongToCategory]);
                this.deleteByIDs(deleteIDs).subscribe((res) => { console.log('delete attachments ids:', deleteIDs) })
            }
            const formData: FormData = new FormData();
            for (let i = 0; i < files.length; i++) {
                formData.append('file', files[i], files[i].name);
            }
            formData.append("belongToCategory", belongToCategory);
            formData.append("belongToID", belongToID);
            return this.httpClient.post(`${AppSettings.server_base}/common/attachment`, formData);
        }

        deleteAttachment(attachment) {
            let header = _.cloneDeep(AppSettings.httpServerHeader);
            header.params = new HttpParams()
            .set('id', attachment.id)
            .set('belongToID', attachment.belongToID)
            .set('belongToCategory', attachment.belongToCategory);
            return this.httpClient.delete(`${AppSettings.server_base}/common/attachment-return`, header);
        }

        
        deleteFile(id): Observable<any> {
            let header = _.cloneDeep(AppSettings.httpServerHeader);
            header.params = new HttpParams().set('id', id);
            return this.httpClient.delete(`${AppSettings.server_base}/common/attachment`, header);
        }

        deleteByIDs(ids:any[]):Observable<any> {
            let header = _.cloneDeep(AppSettings.httpServerHeader);
            header.params = new HttpParams();
            header.params = header.params.set('id', ids.join(','));
            return this.httpClient.delete(`${AppSettings.server_base}/common/attachment`, header);
        }

        getOriginalAttachmentIDs(attachmentField) {
            let ids = _.map(attachmentField, 'id');
            console.log(ids);
            return ids;
        }
    }

